package com.yuexunit.finance.system.action.v1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Singleton;
import com.yuexunit.core.BusinessException;
import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.fs.domain.FileEntry;
import com.yuexunit.fs.service.TransferService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.web.annotation.ActionServlet;

/**
 *@version 创建时间：2016年12月13日 下午6:32:09
 *@author wenwenlong
 *类说明
 */

@ActionServlet({"/api/[^/]+/newDownloadFile.json"})
@Singleton
public class NewDownloadFileAction extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		TransferService fileService = ComponentFactory.loadClass(TransferService.class);

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		String fileUuids = request.getParameter("fileUuids");
		if (fileUuids == null || "".equals(fileUuids.trim())) {
			throw new BusinessException("请选择需要下载的文件！");
		}
		String[] fs = fileUuids.split(",");
		//生成的ZIP文件名为download.zip
		String strZipName = "download.zip";
		response.setContentType("application/x-msdownload" ); // 通知客户文件的MIME类型：  
        response.setHeader("Content-disposition" , "attachment;filename=" + strZipName);  
		byte[] buffer = new byte[1024];
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipName));
		int i = 1;
		for (String f : fs) {
			FileEntry fe = fileService.inquireFileEntry(f);
			String filePath = ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe.getUri();
			File file = new File(filePath);
			FileInputStream fis = new FileInputStream(file);
			
			try {
				out.putNextEntry(new ZipEntry(file.getName()));
			} catch (ZipException e) {
				out.putNextEntry(new ZipEntry(i + file.getName()));
				i++;
			}

			int len;
			while((len = fis.read(buffer))>0) {
				out.write(buffer,0,len);
			}
			fis.close();
			out.closeEntry();
		}
		out.close();
		System.out.println("生成download.zip成功");
	}

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}
